package com.shiwaixiangcun.customer.network

import android.content.Context
import android.support.v4.app.FragmentManager
import android.widget.Toast
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.HttpParams
import com.lzy.okgo.model.Response
import com.lzy.okgo.request.base.Request
import com.shiwaixiangcun.customer.Config
import com.shiwaixiangcun.customer.ConfigSps
import com.shiwaixiangcun.customer.ui.dialog.LoadingDialog
import com.shiwaixiangcun.customer.utils.AppSharePreferenceMgr
import com.shiwaixiangcun.customer.utils.MD5Util
import org.jetbrains.annotations.NotNull

/**
 * Author   Administrator
 * Date     2018/4/9
 * Desc     eg
 *
 * @author Administrator
 */
class NetworkHelper(private val mContext: Context, private val mFragmentManager: FragmentManager) {
    private var strToken: String? = null


    /**
     * 不带Token的Request请求
     */
    fun getRequest(requestUrl: String, params: HttpParams, isShowLoading: Boolean, listener: NetWorkHelperBack?) {
        val loadingDialog = LoadingDialog()
        val signString = sign(params)
        if (!signString?.isBlank()!!) {
            params.put("sign", signString)
        }
        OkGo.get<String>(requestUrl)
                .params(params)
                .execute(object : StringCallback() {
                    override fun onStart(request: Request<String, out Request<*, *>>?) {
                        super.onStart(request)
                        if (isShowLoading) {
                            loadingDialog.showLoadingDialog(mFragmentManager, "loadDialog")
                        }
                    }

                    override fun onFinish() {
                        super.onFinish()
                        if (isShowLoading && loadingDialog.isVisible) {
                            loadingDialog.dismissAllowingStateLoss()
                        }
                    }

                    override fun onSuccess(response: Response<String>) {
                        listener?.requestSuccess(response.body())

                    }

                    override fun onError(response: Response<String>) {
                        super.onError(response)
                        Toast.makeText(mContext, "服务器异常", Toast.LENGTH_SHORT).show()
                        listener?.requestFail()
                    }
                })
    }


    /**
     * 带Token的Request请求
     *
     */
    fun getRequestWithToken(@NotNull requestUrl: String, isShowLoading: Boolean, params: HttpParams, @NotNull listener: NetWorkHelperBack?) {
        strToken = AppSharePreferenceMgr.get(mContext, ConfigSps.CURRENT_TOKEN, "") as String
        params.put("access_token", strToken)
        getRequest(requestUrl, params, isShowLoading, listener)
    }


    /**
     * post请求  不带Token
     */
    fun postRequest(requestUrl: String, params: HttpParams, isShowLoading: Boolean, listener: NetWorkHelperBack?) {
        val loadingDialog = LoadingDialog()
        val signString = sign(params)
        if (!signString?.isBlank()!!) {
            params.put("sign", signString)
        }
        OkGo.post<String>(requestUrl)
                .params(params)
                .isSpliceUrl(true)
                .execute(object : StringCallback() {
                    override fun onStart(request: Request<String, out Request<*, *>>?) {
                        super.onStart(request)
                        if (isShowLoading) {
                            loadingDialog.showLoadingDialog(mFragmentManager, "loadDialog")
                        }
                    }

                    override fun onFinish() {
                        super.onFinish()
                        if (isShowLoading && loadingDialog.isVisible) {
                            loadingDialog.dismissAllowingStateLoss()
                        }
                    }

                    override fun onSuccess(response: Response<String>) {
                        listener?.requestSuccess(response.body())

                    }

                    override fun onError(response: Response<String>) {
                        super.onError(response)
                        Toast.makeText(mContext, "服务器异常", Toast.LENGTH_SHORT).show()
                        listener?.requestFail()
                    }
                })
    }

    /**
     * post请求  带token
     *
     * @param requestUrl
     * @param params
     * @param listener
     */
    fun postRequestWithToken(requestUrl: String, isShowLoading: Boolean, params: HttpParams, listener: NetWorkHelperBack?) {
        strToken = AppSharePreferenceMgr.get(mContext, ConfigSps.CURRENT_TOKEN, "") as String
        params.put("access_token", strToken)
        postRequest(requestUrl, isShowLoading = isShowLoading, params = params, listener = listener)
    }


    /**
     * delete请求
     * *
     * @param requestUrl
     * @param params
     * @param listener
     */
    fun deleteRequest(requestUrl: String, isShowLoading: Boolean, params: HttpParams, listener: NetWorkHelperBack?) {
        val loadingDialog = LoadingDialog()
        val signString = sign(params)
        if (!signString?.isBlank()!!) {
            params.put("sign", signString)
        }
        OkGo.delete<String>(requestUrl)
                .params(params)
                .isSpliceUrl(true)
                .execute(object : StringCallback() {
                    override fun onStart(request: Request<String, out Request<*, *>>?) {
                        super.onStart(request)
                        if (isShowLoading) {
                            loadingDialog.showLoadingDialog(mFragmentManager, "loadDialog")
                        }
                    }

                    override fun onFinish() {
                        super.onFinish()
                        if (isShowLoading && loadingDialog.isVisible) {
                            loadingDialog.dismissAllowingStateLoss()
                        }
                    }

                    override fun onSuccess(response: Response<String>) {
                        listener?.requestSuccess(response.body())

                    }

                    override fun onError(response: Response<String>) {
                        super.onError(response)
                        Toast.makeText(mContext, "服务器异常", Toast.LENGTH_SHORT).show()
                        listener?.requestFail()
                    }
                })
    }


    /**
     * delete请求
     */
    fun deleteRequestWithToken(requestUrl: String, isShowLoading: Boolean, params: HttpParams, listener: NetWorkHelperBack) {
        strToken = AppSharePreferenceMgr.get(mContext, ConfigSps.CURRENT_TOKEN, "") as String
        params.put("access_token", strToken)
        deleteRequest(requestUrl, isShowLoading, params, listener)
    }

    /**
     * get请求
     *
     * @param requestUrl
     * @param params
     * @param listener
     */
    fun putRequestWithoutToken(requestUrl: String, isShowLoading: Boolean, params: HttpParams, listener: NetWorkHelperBack) {
        strToken = AppSharePreferenceMgr.get(mContext, ConfigSps.CURRENT_TOKEN, "") as String
        params.put("access_token", strToken)

        putRequest(requestUrl, isShowLoading, params, listener)
    }

    /**
     * get请求
     *
     * @param requestUrl
     * @param params
     * @param listener
     */
    fun putRequest(requestUrl: String, isShowLoading: Boolean, params: HttpParams, listener: NetWorkHelperBack?) {
        val loadingDialog = LoadingDialog()
        OkGo.put<String>(requestUrl)
                .params("access_token", strToken)
                .params(params)
                .execute(object : StringCallback() {
                    override fun onStart(request: Request<String, out Request<Any, Request<*, *>>>?) {
                        super.onStart(request)
                        if (isShowLoading) {
                            loadingDialog.showLoadingDialog(mFragmentManager, "loadDialog")
                        }
                    }

                    override fun onFinish() {
                        super.onFinish()
                        if (isShowLoading && loadingDialog.isVisible) {
                            loadingDialog.dismissAllowingStateLoss()
                        }
                    }

                    override fun onSuccess(response: Response<String>) {
                        if (isShowLoading) {
                            listener?.requestSuccess(response.body())
                        }
                    }

                    override fun onError(response: Response<String>) {
                        super.onError(response)
                        Toast.makeText(mContext, "服务器异常", Toast.LENGTH_SHORT).show()
                    }
                })
    }


    /**
     * 登录页面
     *
     * @param loginUrl
     * @param params
     * @param listener
     */
    fun login(loginUrl: String, params: HttpParams, listener: NetWorkHelperBack?) {
        val loadingDialog = LoadingDialog()


        OkGo.post<String>(loginUrl)
                .params(params)
                .params("client_secret", "2692e5ef9dc34482b5993a311f086090")
                .params("grant_type", "password")
                .params("scope", "servicecenter")
                .params("client_id", "824bce609110472a9dcf837ada0053e1")
                .execute(object : StringCallback() {
                    override fun onStart(request: Request<String, out Request<*, *>>?) {
                        super.onStart(request)
                        loadingDialog.showLoadingDialog(mFragmentManager, "loadDialog")
                    }

                    override fun onSuccess(response: Response<String>) {
                        listener?.requestSuccess(response.body())

                    }

                    override fun onError(response: Response<String>) {
                        super.onError(response)
                        Toast.makeText(mContext, "服务器异常", Toast.LENGTH_SHORT).show()
                    }

                    override fun onFinish() {
                        super.onFinish()
                        loadingDialog.dismiss()
                    }
                })
    }

    /**
     * 对参数进行签名
     */

    private fun sign(params: HttpParams): String? {
        val stringBuilder = StringBuilder()
        val sortedDescending = params.urlParamsMap.keys.sorted()


        if (sortedDescending.size == 1) {
            if (sortedDescending[0] == "access_token") {
                return ""
            }
        }
        for (key in sortedDescending) {
            if (key != "access_token") {
                stringBuilder.append("$key=").append(params.urlParamsMap.getValue(key)).append("&")
            }

        }
        stringBuilder.append("signkey=").append(Config.SIGN)
        val toString = stringBuilder.toString()
        val replace = toString.replace("[", "").replace("]", "")
        val signString = MD5Util.md5(replace)
        return signString
    }


    /**
     * 请求回调
     */
    interface NetWorkHelperBack {
        /**
         * 网络请求成功
         *
         * @param json
         */
        fun requestSuccess(json: String)

        /**
         * 网络请求失败
         */
        fun requestFail()


    }


    class Builder {

        fun build() {

        }

    }
}

